package com.mojo.concurrent.concurrent_01_thread;

import java.util.concurrent.TimeUnit;

/**
 演示
 * jps查看线程
 * jstack pid 查看线程详情
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class ThreadDemo02 {
    public static void main(String[] args) {
        new Thread(new ThreadDemo02.TimeWaiting(), "TimeWaitingThread").start();
        new Thread(new ThreadDemo02.Waiting(), "WaitingThread").start();
        // 使用两个Blocked线程，一个获取锁成功，另一个被阻塞
        new Thread(new ThreadDemo02.Blocked(), "BlockedThread-1").start();
        new Thread(new ThreadDemo02.Blocked(), "BlockedThread-2").start();
    }

    // 该线程不断地进行睡眠
    static class TimeWaiting implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }
    }

    // 该线程在Waiting.class实例上等待
    static class Waiting implements Runnable {
        @Override
        public void run() {
            while (true) {
                synchronized (ThreadDemo02.Waiting.class) {
                    try {
                        ThreadDemo02.Waiting.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    // 该线程在Blocked.class实例上加锁后，不会释放该锁
    static class Blocked implements Runnable {
        public void run() {
            synchronized (ThreadDemo02.Blocked.class) {
                while (true) {
                    try {
                        TimeUnit.SECONDS.sleep(100);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
    }
}
